const verify = require('../services/verifyPassword')
const getUserInfo = require('../services/getUserInfo')
const Collect = require('../model/Collect')
const Article = require('../model/Article')
const Reading = require('../model/Reading')
const User = require('../model/User')

module.exports = {
    toLogin: async (ctx, next) => {
        await ctx.render('login')
    },

    login: async (ctx, next) => {
        try {
            let postDate = ctx.request.body,
                account = postDate.account,
                password = postDate.password,
                result = await verify(account, password)
            if (result) {
                ctx.session.currentUser = account // 保存session
                const info = await getUserInfo(account)
                ctx.json(info)
            } else {
                ctx.body = {
                    'statusCode': false
                }
            }
        } catch (err) {
            console.log(err)
            ctx.body = {
                'statusCode': false
            }
        }
    },
    getStatus:async (ctx, next) => {
        const user = ctx.session.currentUser
        if (user) {
            const info = {
                statusCode: 1
            }
            ctx.json(info)
        } else {
            const info = {
                statusCode: 0
            }
            ctx.json(info)
        }
    },

    userInfo: async (ctx, next) => {
        const user = ctx.session.currentUser
        if (user) {
            const info = await getUserInfo(user)
            ctx.json(info)
        } else {
            ctx.response.status = 302
        }
    },

    out: async (ctx, next) => {
        ctx.session.currentUser = null
        let info = {
            statusCode: Boolean
        }
        try {
            info.statusCode = 1
            ctx.json(info)
        } catch (err) {
            info.statusCode = 0
            ctx.json(info)
        }
    }

}